// 全局参数
let AppConstants= Ext.widget("AppConstants");
Ext.application({
	name : 'Dashboard',
	launch : function() {
		Ext.tip.QuickTipManager.init(true,{showDelay:200,dismissDelay:0});
		let qtipTpl = new Ext.XTemplate(
			'<div style="margin:5px;font-size:12px;">',
			'<tpl for=".">',
			'<span style="font-weight:bold;">{propName}: </span>{propValue}<br/>',
			'</tpl>',
			'</div>'
		);
		let changeConent = false;
		window.onbeforeunload = function(e) {
			e = e || window.event;
			if (changeConent) {
				// IE 和 Firefox
				if (e) {
					e.returnValue = "对不起，页面数据已做修改，尚未保存，确定要刷新或离开本页面？";
				}
				// Safari浏览器
				return "对不起，页面数据已做修改，尚未保存，确定要刷新或离开本页面？";
			}
		};
		let datefield1 = {
			xtype : 'datefield',
			format : 'Y-m-d',
			listeners : {
				'dirtychange' : function(datefield, isDirty, eOpts) {
					// console.log('datefield:%o, isDirty:%o, eOpts:%o', datefield, isDirty, eOpts);
					console.log('dirtychange:%o', isDirty);
				},
				'change' : function(datefield, newValue, oldValue, eOpts) {
					console.log('change:%o---->%o', oldValue, newValue);
				},
	        	'blur' : function(){
	        		console.log('date blur')
	        		let grid = this.findParentByType('grid');
	        		dashboardGrid.updateReloadAble(true);
	        	},
				'expand' : function(){
					console.log('date expand')
					let grid = this.findParentByType('grid');
					dashboardGrid.updateReloadAble(false);
				}
			}
		};
		let numberField1 = {
			xtype : 'numberfield',
			minValue : 0.5,
			step : 0.5,
			allowDecimals : true,
			decimalPrecision : 1,
			listeners : {
				'blur' : function() {
					console.log('numberfield blur')
					let grid = this.findParentByType('grid');
					dashboardGrid.updateReloadAble(true);
				}
			},
		};
		let numberField2 = {
			xtype : 'numberfield',
			minValue : 0,
			maxValue : 100,
			step : 5,
			listeners : {
				'blur' : function() {
					console.log('numberfield blur')
					let grid = this.findParentByType('grid');
					dashboardGrid.updateReloadAble(true);
				}
			},
		};

		let pageSizeCmb = Ext.create('Dashboard.PageSizeCmb', {
			xtype: 'PageSizeCmb',
			id : 'pageSizeCmb',
			fieldLabel: '每页行数:',
			width : 150,
			value : 100,
			labelAlign : 'right',
			listeners : {
				'change' : function(cmb, newValue, oldValue, eOpts) {
					dashboardStore.setPageSize(newValue);
					dashboardStore.load({
						params: {
					        start: 0,
					        rows: newValue
					    }
					});
				},
			}
		});
		
		let dashboardStore = Ext.create('Ext.data.Store', {
			storeId: 'dashboardStore',
			pageSize : pageSizeCmb.getValue(),
			autoLoad: {
		    	params: {
			        start: 0,
			        rows: pageSizeCmb.getValue()
			    }
		    },
		    proxy: {
		        type: "ajax",
		        url: "/dashboard/load",
		        reader: {
		            type: 'json',
		            rootProperty: "data.data",
		            totalProperty: 'data.total',
		            idProperty: 'taskId',
		        },
		        limitParam : 'rows',
		        extraParams: {
		        	 orderByClause : 'task_id desc'
				}
		    },
		    listeners : {
				'beforeload' : function(store) {
					let proxy = store.getProxy();
					let applicationCmb = Ext.getCmp('application-search');
					let taskTypeCmb = Ext.getCmp('task-type-search');
					let taskNamekeywordsCmb = Ext.getCmp('task-name-keywords-search');
					let monthCmb = Ext.getCmp('monthCmb');
					let memeberCmb = Ext.getCmp('memeberCmb-search');
					let memeberTestCmb = Ext.getCmp('memeberCmb-search2');
					let statusCmb = Ext.getCmp('statusCmb-search');
					let applications = applicationCmb.getValue();
					if (applications) {
						if (applications.length > 1) {
							proxy.setExtraParam('applications', applications);
						}else{
							proxy.setExtraParam('application', applications);
						}
					}
					let monthValue = monthCmb && monthCmb.getValue();
					if (monthValue) {
						if ('全选' === monthValue) {
							monthValue = '';
						}
						proxy.setExtraParam('month', monthValue);
					}
					let taskType = taskTypeCmb && taskTypeCmb.getValue();
					if (taskType) {
						if ('全选' === taskType) {
							taskType = '';
						}
						proxy.setExtraParam('taskType', taskType);
					}
					let memebers = [];
					if (memeberCmb && memeberCmb.getValue()) {
						proxy.setExtraParam('memeber', memeberCmb.getValue());
					} else {
						proxy.setExtraParam('memeber', '');
					}
					if (memeberTestCmb && memeberTestCmb.getValue()) {
						proxy.setExtraParam('testMemeber', memeberTestCmb.getValue());
					} else {
						proxy.setExtraParam('testMemeber', '');
					}
					proxy.setExtraParam('taskNameKeywords', taskNamekeywordsCmb && taskNamekeywordsCmb.getValue());
					proxy.setExtraParam('statusList', statusCmb && statusCmb.getValue());
				},
				'load' : function(cmp, newValue, oldValue, eOpts) {
					let searchBtn = Ext.getCmp('searchBtn');
					searchBtn && searchBtn.setDisabled(false);
				},
			}
		});
		
		// 是否锁定列
		let lockTaskMainInfo = AppConstants.getLockTaskMainInfo();
		
		let gridItems =[
//			{ xtype: 'checkcolumn', text: 'Active', renderer : false },
			{ text : '行号', editor : false, width : 50, locked: lockTaskMainInfo, renderer : function(value, metaData, record, rowIdx, colIdx, store) {
					metaData.tdStyle = "vertical-align:middle;";
					if (store.lastOptions.params != null) {
						let pageindex = store.lastOptions.params.start;
						return pageindex + rowIdx + 1;
					} else {
						return rowIdx + 1;
					}
				}
			},
			{ text : 'id', dataIndex : 'taskId', editor : false, hidden : true },
			{ text : '类型', dataIndex : 'taskType', editor : { xtype : 'TaskTypeCmb' }, width : 60, locked: lockTaskMainInfo, },
			{ text : '应用', dataIndex : 'applications', editor : { xtype : 'ApplicationCmb'}, locked: lockTaskMainInfo, },
			{ text : '任务名称', dataIndex : 'taskName', align : 'left', width : 200, locked: lockTaskMainInfo,
				editor : { xtype : 'textareafield', grow:true, allowBlank : false,
					listeners: {
			        	'blur' : function(){
			        		console.log('textareafield blur')
			        		let grid = this.findParentByType('grid');
							dashboardGrid.updateReloadAble(true);
			        	}
					} 
				},
				renderer : function(value, metaData, record, rowIdx, colIdx, store){
					try{
						value = value.replace(/(\r\n|\n|\r)/gm, '<br/>');
						let tips=[];
						let columns = Ext.getCmp('dashboardGrid').getColumnManager().columns;
						let keyName = {};
						let quikTipFields = AppConstants.getQuikTipFields();
						columns.forEach(v => {
							if (Ext.Array.contains(quikTipFields, v.dataIndex)) {
								keyName[v.dataIndex] = v.text;
							}
						});
						let taskStatusMap = AppConstants.loadParamMap('taskStatus');
						for (let i in record.data) {
							let propName = keyName[i];
							if (keyName[i]) {
								let val = record.data[i];
								if (i == 'status') {
									val = taskStatusMap[val];
								} else if (i == 'progress') {
									val = val + "%";
								}
								tips.push({
									"propName" : propName,
									"propValue" : val
								});
							}
						}
						let qtip = qtipTpl.apply(tips);
						qtip = Ext.String.htmlEncode(qtip);
						metaData.tdAttr = 'data-qtip="' + qtip + '"';
						metaData.tdStyle = "vertical-align:middle;";
						return value;
					}catch(e){
						return value;
						console.log(e);
					}
				}
			},
			//参数类型(1.参数类型,2.任务状态,3.任务类型,4.月度范围,5.友情链接,6.滚动tip,7.优先级,8.jira前缀,9.项目列表,10.开发成员,11.测试成员)
			{ text : '开发', dataIndex : 'developers', editor : { xtype : 'MemberCmb', editable:true, paramType : AppConstants.getDeveloper() }, align : 'left', width : 80 },
			{ text : '测试', dataIndex : 'testerses', editor : { xtype : 'MemberCmb', editable:true, paramType : AppConstants.getTester() }, align : 'left', width : 80 },
			{ text : '状态', dataIndex : 'status', editor : { xtype : 'StatusCmb' }, width : 50, align : 'left' },
			{ text : '进度', dataIndex : 'progress', editor : numberField2, width : 70, renderer : function(value, metaData, record) {
					let id = Ext.id();
					metaData.tdAttr = 'data-qtip="' + value + '%"';
					metaData.tdStyle = "vertical-align:middle;";
					Ext.defer(function() {
						Ext.widget('progressbar', {
							renderTo : id,
							value : value / 100,
							height : 20,
							width : 60,
							text : value + '%'
						});
					}, 50);
					return Ext.String.format('<div id="{0}"></div>', id);
				}
			},
			{ text : '优先级', dataIndex : 'priority', editor : { xtype : 'PrioritiyCmb' }, width : 50 },
			{ text : '文档', dataIndex : 'isNeedDoc', editor : { xtype : 'YesOrNoCmb' }, width : 40 },
			{ text : '评审', dataIndex : 'isNeedReview', editor : { xtype : 'YesOrNoCmb' }, width : 40 },
			{ text : 'jira', dataIndex : 'jiraId', width : 75 },
			{ text : '工作量', dataIndex : 'workDays', editor : numberField1, width : 50, hidden : true },
			{ text : '归属月份', dataIndex : 'month', editor : false, hidden : true },
			{ text : '计划开始', dataIndex : 'planStartDate', editor : datefield1, width : 65 },
			{ text : '实际开始', dataIndex : 'realStartDate', editor : datefield1, hidden : true },
			{ text : '计划结束', dataIndex : 'planEndDate', editor : datefield1, width : 65 },
			{ text : '实际结束', dataIndex : 'realEndDate', editor : datefield1, hidden : true },
			{ text : '计划测试', dataIndex : 'planTestDate', editor : datefield1, width : 65 },
			{ text : '实际测试', dataIndex : 'realTestDate', editor : datefield1 },
			{ text : '计划上线', dataIndex : 'planOnlieDate', editor : datefield1, width : 65 },
			{ text : '实际上线', dataIndex : 'realOnlieDate', editor : datefield1, hidden : true },
			{ text : '文档链接', dataIndex : 'docLink' },
			{ text : '备注', dataIndex : 'remark', align : 'left', width : 200, editor : 
				{ xtype : 'textareafield', grow:true, allowBlank : false,
					listeners: {
			        	'blur' : function(){
			        		console.log('textareafield blur')
			        		let grid = this.findParentByType('grid');
							dashboardGrid.updateReloadAble(true);
			        	}
					} 
				}
			},
			{ text : '延期', dataIndex : 'isDelay', editor : { xtype : 'YesOrNoCmb' }, width : 40 },
			{ text : '延期原因', dataIndex : 'delayReason', width : 200, align : 'left', width : 200, editor : 
				{ xtype : 'textareafield', grow:true, allowBlank : false,
					listeners: {
			        	'blur' : function(){
			        		console.log('textareafield blur')
			        		let grid = this.findParentByType('grid');
							dashboardGrid.updateReloadAble(true);
			        	}
					} 
				}
			},
			{ text : '创建时间', dataIndex : 'createTime', editor : false, xtype:'datecolumn', dateFormat:'Y-m-d H:i:s', width : 130 },
			{ text : '更新时间', dataIndex : 'updateTime', editor : false, xtype:'datecolumn', format:'Y-m-d H:i:s', hidden : true },
			{ text : 'user_id', dataIndex : 'userId', hidden : true },
			{ text : 'username', dataIndex : 'username', hidden : true },
			{ text : 'update_user_id', dataIndex : 'updateUserId', hidden : true },
			{ text : 'update_username', dataIndex : 'updateUsername', hidden : true },
			{ text : 'is_deleted', dataIndex : 'isDeleted', hidden : true },
			{ text : '操作', dataIndex : '', align: "center", width : 60, editor : false, hidden : true,
				renderer: function (value, metaData, record) {
					let id = metaData.record.id;
				    metaData.tdAttr = 'data-qtip="删除当前行"';
					metaData.tdStyle = "vertical-align:middle;";
				    Ext.defer(function () {
				        Ext.widget('button', {
				            renderTo: id,
							text: '<i class="fa fa-times">删除</i>',
							handler : function() {
								let grid = Ext.getCmp('dashboardGrid');
								if (grid) {
									grid.delByTaskId(record);
								}
							}
						});
				    }, 50);
				    return Ext.String.format('<div id="{0}"></div>', id);
				}
			}
		];
		// 隐藏列
		let hiddenFileds = AppConstants.getHiddenFileds();
		gridItems.forEach(v => {
			if (Ext.Array.contains(hiddenFileds, v.dataIndex)) {
				v.hidden = true;
			}
		});
		let dashboardGrid = Ext.create('Ext.grid.Panel', {
			// title : '项目看板',
			region:'center',
			id: 'dashboardGrid',
			store : dashboardStore,
			reloadAble : true,
			viewConfig:{
				enableTextSelection : true,
				forceFit : false,
				stripeRows : false,
				markDirty : false,
				getRowClass : changeRowClass
			},
			scrollable : true,
			columns : {
				items : gridItems,
				defaults: {
			        editor : {
			        	xtype : 'textfield',
				        listeners: {
				        	'blur' : function(){
				        		console.log('textfield blur')
				        		let grid = this.findParentByType('grid');
								dashboardGrid.updateReloadAble(true);
				        	}
				        }
			        },
			        align : 'center',
					renderer : function(value, metaData, record, rowIdx, colIdx, store) {
						if (null == value) {
							return;
						}
						let showValue;
						let dataIndex = this.getColumnManager().getHeaderAtIndex(colIdx).dataIndex;
						if ('isNeedDoc' == dataIndex || 'isDelay' == dataIndex || 'isNeedReview' == dataIndex) {
							showValue = value == 1 ? '是' : '否';
						} else if ('status' == dataIndex) {
							let taskStatusMap = AppConstants.loadParamMap('taskStatus');
							showValue = taskStatusMap[value];
						} else if ('priority' == dataIndex) {
							let prioritiyMap = AppConstants.loadParamMap('prioritiyLevel');
							showValue = prioritiyMap[value] || value;
						} else if ('taskType' == dataIndex) {
							showValue = AppConstants.loadParamMap('taskType') [value] || value;
						} else if ('developers' == dataIndex) {
							let developerMap = AppConstants.loadParamMap('developer');
							let valueArr = Ext.isArray(value) ? value : [ value ];
							let names = [];
							for (let i in valueArr) {
								let v = valueArr[i];
								let name = developerMap[v] || v;
								names.push(name);
							}
							showValue = names.join(',');
						} else if ('testerses' == dataIndex) {
							let testersMap = AppConstants.loadParamMap('tester');
							let valueArr = Ext.isArray(value) ? value : [ value ];
							let names = [];
							for (let i in valueArr) {
								let v = valueArr[i];
								let name = testersMap[v] || v;
								names.push(name);
							}
							showValue = names.join(',');
						} else if ('applications' == dataIndex) {
							let applicationMap = AppConstants.loadParamMap('application');
							let valueArr = Ext.isArray(value) ? value : [ value ];
							let names = [];
							for (let i in valueArr) {
								let v = valueArr[i];
								let name = applicationMap[v] || v;
								names.push(name);
							}
							showValue = names.join(',');
						}
						metaData.tdAttr = 'data-qtip="' + Ext.String.htmlEncode(showValue || value) + '"';
						metaData.tdStyle = "vertical-align:middle;";
						// 自动换行
						if ('taskName' == dataIndex || 'remark' == dataIndex || 'createTime' == dataIndex) {
							metaData.style = 'overflow-y:auto;padding: 3px 6px;text-overflow: ellipsis;white-space: nowrap;white-space:normal;line-height:20px;';
						} else if (dataIndex.endsWith('Date')) {
							if (!value) {
								return "";
							}
							if (Ext.isDate(value)) {
								showValue = value;
							}else{
								showValue = new Date(Date.parse(value));
							}
							metaData.tdAttr = 'data-qtip="' + Ext.String.htmlEncode(Ext.Date.dateFormat(showValue, 'Y-m-d')) + '"';
							return Ext.Date.dateFormat(showValue, 'm-d');
						}
						return showValue || value;
					}
				}
			},
//			selModel: 'cellmodel',
			plugins:[
				{
					ptype : 'cellediting',
					clicksToEdit : 2,
				}
			],
			// 换行参考https://blog.csdn.net/u013754950/article/details/41038849
		    tbar: [
		    	{ xtype:'ApplicationCmb', id : 'application-search', fieldLabel: '应用', labelWidth : 30, width : 130, labelAlign : 'right' },
		    	{ xtype:'TaskTypeCmb', id : 'task-type-search', fieldLabel: '类型', labelWidth : 30, width : 110, labelAlign : 'right' },
		    	{ xtype:'label',text:'任务关键词:'},
		    	{ xtype:'textfield', id : 'task-name-keywords-search' },
		    	//参数类型(1.参数类型,2.任务状态,3.任务类型,4.月度范围,5.友情链接,6.滚动tip,7.优先级,8.jira前缀,9.项目列表,10.开发成员,11.测试成员)
		    	{ xtype:'MemberCmb', paramType : AppConstants.getTypeByName('developer'), id : 'memeberCmb-search', fieldLabel: '开发人员', labelWidth : 60, width : 140, labelAlign : 'right', multiSelect : false },
		    	{ xtype:'MemberCmb', paramType : AppConstants.getTypeByName('tester'), id : 'memeberCmb-search2', fieldLabel: '测试人员', labelWidth : 60, width : 140, labelAlign : 'right', multiSelect : false },
		    	{ xtype:'StatusCmb', id : 'statusCmb-search', fieldLabel: '状态', labelWidth : 30, width : 110, labelAlign : 'right', multiSelect : true },
		    	{
					xtype: 'combobox',
				    id: 'monthCmb',
					fieldLabel : '月度',
					editable : false,
					allowBlank: true,
					labelWidth: 30,
					width: 110,
				    queryMode: 'local',
				    valueField: 'value',
					labelAlign : "right",
				    displayField: 'value',
				    value : Ext.Date.dateFormat(new Date(), 'Ym'),
				    store : {
				    	fields: ['value'],
					    data: AppConstants.loadParamByName('monthRange')
				    }
				},
		    	{ xtype:'Curdtool' }
		    ],
		    bbar:[
		    	{
		    		xtype: 'panel',
		    		//id: 'scroll-div'
		    		bodyStyle: {
		    			background: '#DCE7F3',
		    			//padding: '5px'
		    		},
		    		border : false,
		    		html : '<div id="slider-tip">'
		    			+ '	<div id="scroll-div" class="scroll-div">'
		    			+ '		<div id="scroll-begin">'
		    			+ '			...'
		    			+ '		</div>'
		    			+ '		<div id="scroll-end"></div>'
		    			+ '	</div>'
		    			+ '</div>',
		    		listeners : {
		    			afterrender : function(p) {
							let tips = '双击单元格进行编辑;选中一行右键点击可查看额外选项;页面定时刷新,若正在编辑中,则会忽略刷新;';
							let scrollBegin = p.el.query('div#scroll-begin')[0];
							let paramCfg = AppConstants.loadParamByName('scrollTip');
							scrollBegin.innerHTML = paramCfg && paramCfg[0].value || tips;
							//要想滑动不停  scroll-begin的内容宽度必须大于scroll_div的宽度
							let speed = 50;
		    				let scroll_begin = document.getElementById("scroll-begin");
		    				let scroll_end = document.getElementById("scroll-end");
		    				let scroll_div = document.getElementById("scroll-div");
		    				scroll_end.innerHTML = scroll_begin.innerHTML;
		    				function Marquee() {
		    					//offsetWidth  width + border + padding
		    					//scrollleft 滑动条起点向右滑动的距离 当一个div显示完后 迅速重置滑动条的起点为最左端 重新显示div内容
		    					if (scroll_end.offsetWidth - scroll_div.scrollLeft <= 0) {
		    						scroll_div.scrollLeft -= scroll_begin.offsetWidth;
		    					} else {
		    						scroll_div.scrollLeft++;
		    					}
		    				}
		    				let MyMar = setInterval(Marquee, speed);
		    				scroll_div.onmouseover = function() {
		    					clearInterval(MyMar);
		    				}
		    				scroll_div.onmouseout = function() {
		    					MyMar = setInterval(Marquee, speed);
		    				}
		    			}
		    		}
				},
				{
		    		xtype: 'panel',
		    		bodyStyle: {
		    		    background: '#DCE7F3',
		    		    padding:'0 0 0 20px'
		    		    //padding: '5px'
		    		},
		    		border : false,
		    		html: AppConstants.loadFriendLink()
				},
		    	"->",
		    	{
					xtype : "button",
					glyph : 'xf013@FontAwesome',
					text : "配置",
					//tooltip : "系统参数配置",
					handler : function(btn) {
						Ext.create('Ext.window.Window', {
				    	    title: '系统参数配置',
				    	    layout: 'fit',
				    	    id : 'addWindow',
				            modal: true,
				            width : 780,
				            height : window.innerHeight-100,
				            resizable: true,
				            plain: true,
				            contentEl : Ext.DomHelper.append(document.body, {
								tag : 'iframe',
								style : "border 0px none;scrollbar:true",
								src : 'settings.html',
								height : "100%",
								width : "100%"
							})
				    	}).show();
					}
				},
		    	"-",
		    	{
	                xtype: 'pagingtoolbar',
	                store: dashboardStore,
	                displayInfo: true,
					items : [ 
						{
							xtype : "splitbutton",
							text : "导出",
							tooltip : "导出文件(默认导出当前页)",
							handler : function(btn) {
								dashboardGrid.exportExcel(dashboardGrid, btn, 1);
							},
							menu : {
								items : [ {
									text : "导出当前页(默认)",
									handler : function(btn) {
										dashboardGrid.exportExcel(dashboardGrid, btn, 1);
									}
								},'-', {
									text : "导出全部",
									handler : function(btn) {
										dashboardGrid.exportExcel(dashboardGrid, btn, 3);
									}
								} ]
							}
						},
						pageSizeCmb
					]
				},
	            "-",
	            {
		    		xtype: 'panel',
		    		id : 'workState',
		    		bodyStyle: {
		    		    background: '#DCE7F3',
		    		    //padding: '5px'
		    		},
		    		border : false,
		    		html : ''
		    	},
	            {
		    		xtype: 'panel',
		    		id : 'refreshState',
		    		bodyStyle: {
		    			background: '#DCE7F3',
		    			//padding: '5px'
		    		},
		    		border : false,
		    		html : '',
					listeners : {
						'afterrender' : function(p, eOpts) {
							let interval = dashboardGrid.autoFresh(p, 120);
							p.el.on('click', function(a, b) {
								let msg = '<span class="red">关闭</span>自动刷新';
								if (interval) {
									Ext.Msg.confirm("自动刷新开关", msg, function(opt) {
										if ('yes' == opt) {
											p.setHtml('<a class="panel-link" href="#">自动刷新关闭</a>');
											clearInterval(interval);
											interval = 0;
										}
									});
									return;
								}
								msg = '<span class="green">开启</span>自动刷新,输入自动刷新间隔秒数';
								Ext.Msg.prompt("自动刷新开关", msg, function(opt, a) {
									if ('ok' == opt) {
										interval = dashboardGrid.autoFresh(p, a || 120);
									}
								});
							});
						}
					}
				},
		    ],
		    listeners: {
				'beforeedit' : function(editor, context, eOpts) {
						console.log('beforeedit...');
						dashboardGrid.updateReloadAble(false);
						changeConent = true;
					},
				'canceledit ' : function(editor, context, eOpts) {
					console.log('canceledit...');
					dashboardGrid.updateReloadAble(true);
					changeConent = false;
				},
				'edit' : function(editor, context) {
					console.log('edit fired...');
					let taskId = context.record.data.taskId;
					let field = context.column.dataIndex;
					let originalValue = context.originalValue;
					let value = context.value;
					if (isValueChanged(field, originalValue, value)) {
						dashboardGrid.updateFiled(taskId, field, originalValue, value);
					}
				}
			},
			autoFresh : function(p, t) {
				let content = '<a class="panel-link" href="#">自动刷新还有</a> <span class="refresh-time">{}</span> s';
				p.setHtml(content);
				let refresTimeLink = p.el.query('span.refresh-time')[0];
				//还有几秒；
				let i = t;
				let stopped = false;
				let interval = setInterval(function() {
					if (stopped) {
						p.setHtml(content);
						refresTimeLink = p.el.query('span.refresh-time')[0];
						stopped = false;
					}
					if (i == 0) {
						i = t;
						if (dashboardGrid.reloadAble) {
							dashboardStore.load();
						} else {
							p.setHtml('编辑中,取消刷新...');
							console.log('编辑中,取消刷新...')
							stopped = true;
						}
					}
					if (!stopped) {
						refresTimeLink.innerHTML = (i - 1);
					}
					i--;
				}, 1000);
				return interval;
			},
			updateReloadAble : function(v){
				console.log('reloadAble:%o-->%o', dashboardGrid.reloadAble, dashboardGrid.reloadAble = v);
				Ext.getCmp('workState').setHtml(v ? '' : '<div class="x-mask-msg-text"><font color="red">编辑中</font>...</div>');
			},
		    showAddWin : function(){
		    	Ext.create('Ext.window.Window', {
		    	    title: '新增任务',
		    	    layout: 'fit',
		    	    id : 'addWindow',
		            modal: true,
		            width:480,
		            height:360,
		            //closeAction:'hide',
		            resizable: true,
		            plain: true,
		    	    items: [
		    	    	{
		    	    		xtype : 'AddForm'
		    	    	}
		    	    ]
		    	}).show();
		    },
			delByTaskId : function(record) {
				let me = this;
				if(!record.getData()){
					Ext.Msg.show({  
					    title:'失败',  
					    msg: '请选中一行',  
					    buttons: Ext.Msg.OK,  
					    icon: Ext.Msg.ERROR
					});
					return;
				}
		    	let taskName = record.getData().taskName;
		    	let taskId = record.getData().taskId;
		    	let msg = '确认删除<span style="color:red;">[' + taskName + ']</span>吗?';
		    	Ext.Msg.confirm("操作确认", msg, function(opt) {
		    		if ('yes' == opt) {
		    			console.log('del,id:%o', taskId) ;
		    			Ext.Ajax.request({
							url : "/dashboard/delete",
							method : 'post',
							params : {taskId:taskId},
							success : function(response, opts) {
								let obj = Ext.decode(response.responseText);
								console.dir(obj);
								me.getStore().load();
							},
							failure : function(response, opts) {
								Ext.Msg.show({  
								    title:'失败',  
								    msg: '数据保存失败',  
								    buttons: Ext.Msg.OK,  
								    icon: Ext.Msg.ERROR
								});
								console.log('server-side failure with status code ' + response.status);
							}
						});
		    		}
		    	});
		    },
		    updateFiled : function(taskId, field, originalValue, value){
		    	let me = this;
		    	console.info('开始更新taskId:%o,field:%o,%o,-->%o', taskId, field, originalValue, value);
				let params = {taskId : taskId};
				dashboardGrid.updateReloadAble(false);
				console.log('updatefiled request start...');
				if (field.endsWith('Date')) {
					if (value) {
						if (!Ext.isDate(value)) {
							value = new Date(Date.parse(value));
						}
					} else {
						value = null;
					}
					value = Ext.Date.dateFormat(value, 'Y-m-d H:i:s');
				} else if ('taskName' == field) {
					//value = value.replace(/(\r\n|\n|\r)/gm, '\\n');
					console.log('taskName',value);
				}
				params[field] = value;
				if (null == value || undefined == value || (value && value.constructor === Array && 0 == value.length)) {
					params.forceNullField = field;
				}
				let wkSt = Ext.getCmp('workState');
				wkSt.setHtml('<div class="x-mask-msg-text">修改中...</div>');
				Ext.Ajax.request({
					url : "/dashboard/update",
					method : 'post',
					jsonData : params,
					callback : function(options,success,reponse){
						//console.log('callback,options:%o,success:%o,reponse:%o',options,success,reponse)
						let result = {
							success : false,
							message : '请求异常'
						};
						try {
							result = Ext.JSON.decode(reponse.responseText);
						} catch (e) {}
						if (result.success) {
							me.getStore().load();
							changeConent = false;
							dashboardGrid.updateReloadAble(true);
							wkSt.setHtml('<font color="green">修改成功</font>');
						} else {
							Ext.Msg.show({  
							    title:'失败',  
							    msg: '数据保存失败',  
							    buttons: Ext.Msg.OK,  
							    icon: Ext.Msg.ERROR
							});
							wkSt.setHtml('<font color="red">修改失败!</font>');
						}
						console.log('updatefiled request end...');
					}
				});
		    },
		    onSearch : function(btn){
		    	btn.setDisabled(true);
		    	Ext.getStore('dashboardStore').load();
		    },
			exportExcel : function(grid, btn, exportType) {
				let columndatas = [],
					queryParams = grid.getStore().proxy.extraParams;
				switch (exportType) {
				// 导出当前页(默认)
				case 1:
					let data = grid.getStore().data;
					data.each(function(record) {
						columndatas.push(record.getData());
					})
					queryParams.page = grid.getStore().currentPage;
					break;
				// 导出选中行
				case 2:
					let records = grid.getSelectionModel().getSelection();
					for (let i in records) {
						let data = records[i].getData();
						columndatas.push(data);
					}
					break;
				// 导出全部
				case 3:
					break;
				default:
					break;
				}
				console.log("queryParams:%o", queryParams);
				if ((0 == columndatas.length && exportType != 3) || 0 == grid.getStore().getTotalCount()) {
					Ext.Msg.show({
						title : '系统提示',
						msg : '要导出的数据内容为空!',
						buttons : Ext.Msg.OK,
						icon : Ext.Msg.INFO
					});
					return;
				}
				if (!Ext.fly("downloadAttachFileForm")) {
					let frm = document.createElement("form");
					frm.id = "downloadAttachFileForm";
					frm.style.display = "none";
					document.body.appendChild(frm);
				}
				Ext.Ajax.request({
					url : "/dashboard/exportExcel",
					isUpload : true,
					form : Ext.fly("downloadAttachFileForm"),
					method : "post",
					params : {
						exportType : exportType,
						columndatas : Ext.encode(columndatas),
						queryParams : Ext.encode(queryParams)
					},
					success : function(response) {
						let rs = {};
						try {
							rs = Ext.decode(response.responseText);
						} catch (e) {
							rs = {
								success : false,
								msg : "程序出错,数据格式异常"
							};
						}
						if (rs.success === false) {
							Ext.Msg.show({
								title : '系统提示',
								msg : "错误:" + rs.msg,
								buttons : Ext.Msg.OK,
								icon : Ext.Msg.INFO
							});
						}
					}
				});
			}
		});
		//为右键菜单添加事件监听器
		dashboardGrid.addListener('rowcontextmenu', function( grid, record, tr, rowIndex, e){ 
		    e.preventDefault(); 
		    rightClick.showAt(e.getXY()); 
		});
		let rightClick = new Ext.menu.Menu({
			id : 'rightClickCont',
			items : [
				{
					id : 'rMenu1',
					text : '刷新',
					glyph : 'xf021@FontAwesome',
					handler : function() {
						dashboardGrid.getStore().load();
					}
				},
				{
					id : 'rMenu2',
					handler : function() {
						dashboardGrid.showAddWin();
					},
					glyph : 'xf067@FontAwesome',
					text : '添加数据',
				},
				{
					id : 'rMenu3',
					handler : function() {
						let record = dashboardGrid.getSelectionModel().getSelected().items[0];
						if (!record) {
							Ext.Msg.show({
								title : '提示',
								msg : '请选中一行',
								buttons : Ext.Msg.OK,
								icon : Ext.Msg.INFO
							});
							return;
						}
						let data = record.getData();
						let taskName = data.taskName;
						let month = Ext.Date.format(new Date(), "Ym");
						let msg = '复制后归属月份为<span style="color:red;">' + month + '</span><br/>确认复制[<span style="color:red;">' + taskName + '</span>]吗?';
						Ext.Msg.confirm("操作确认", msg, function(opt) {
				    		if ('yes' == opt) {
								data.taskId = null;
								data.month = null;
								Ext.Ajax.request({
									url : "/dashboard/add",
									method : 'post',
									jsonData : data,
									success : function(response, opts) {
										let obj = Ext.decode(response.responseText);
										console.dir(obj);
										Ext.Msg.show({
											title : '提示',
											msg : '数据复制成功',
											buttons : Ext.Msg.OK,
											icon : Ext.Msg.INFO,
											fn: function(btn) {
										         if (btn === 'ok') {
										        	 dashboardGrid.getStore().load();
										         }
										     }
										});
									},
									failure : function(response, opts) {
										Ext.Msg.show({
											title : '失败',
											msg : '数据复制失败',
											buttons : Ext.Msg.OK,
											icon : Ext.Msg.ERROR
										});
										console.log('server-side failure with status code ' + response.status);
									}
								});
				    		}
				    	});
					},
					glyph : 'xf0c5@FontAwesome',
					text : '复制数据',
				},
				{
					id : 'rMenu4',
					text : '删除当前行',
					glyph : 'xf00d@FontAwesome',
					handler : function() {
						let record = dashboardGrid.getSelectionModel().getSelected().items[0];
						dashboardGrid.delByTaskId(record);
					}
				},
				{
					id : 'rMenu5',
					text : '打开jira',
					glyph : 'xf08e@FontAwesome',
					handler : function() {
						let record = dashboardGrid.getSelectionModel().getSelected().items[0];
						if (!record || !record.getData().jiraId) {
							Ext.Msg.show({
								title : '失败',
								msg : '未选中或jira编号不存在',
								buttons : Ext.Msg.OK,
								icon : Ext.Msg.ERROR
							});
							return;
						}
						let jiraId = record.getData().jiraId;
						if (jiraId.indexOf('http') < 0) {
							let jiraPrefix = AppConstants.getParamValue('jiraPrefix');
							jiraId = (jiraPrefix || 'http://jira.weidai.work/browse/') + jiraId;
						}
						window.open(jiraId, '_blank');
					}
				},
				{
					id : 'rMenu6',
					text : '查看文档',
					glyph : 'xf070@FontAwesome',
					handler : function() {
						let record = dashboardGrid.getSelectionModel().getSelected().items[0];
						if (!record || !record.getData().docLink) {
							Ext.Msg.show({
								title : '失败',
								msg : '未选中或文档链接不存在',
								buttons : Ext.Msg.OK,
								icon : Ext.Msg.ERROR
							});
							return;
						}
						let docLink = record.getData().docLink;
						window.open(docLink, '_blank');
					}
				}
			]
		});
		let panel = Ext.create('Ext.panel.Panel', {
			fullscreen : true,
			height : window.innerHeight,
			width : window.innerWidth,
			layout : 'border',
			border : 0,
			items : [
				dashboardGrid
			],
			renderTo : Ext.getBody()
		});

		Ext.on('resize', function(width, height) {
			panel.setWidth(width);
			panel.setHeight(height);
		});

	}
});


function isValueChanged(field, originalValue, value) {
	console.log('field:%o,originalValue:%o,value:%o', field, originalValue, value);
	if (null == originalValue && null == value) {
		return false;
	}
	if (null == originalValue && value) {
		return true;
	}
	if ((originalValue || 0 == originalValue) && null == value) {
		return true;
	}
	if (originalValue == value) {
		return false;
	}
	if (value.constructor === Array) {
		if (null == originalValue) {
			return true;
		}
		if (originalValue.constructor === Array) {
			if (value.length != originalValue.length) {
				return true;
			}
		} else if ('string' == typeof originalValue) {
			let originArr = originalValue.split(',');
			if (value.length != originArr.length) {
				return true;
			}
		}
		for (let ii in value) {
			let newV = value[ii];
			let hasSame = false;
			for (var i in originalValue) {
				if (originalValue[i] == newV) {
					hasSame = true;
					break;
				}
			}
			if (!hasSame) {
				return true;
			}
		}
		return false;
	}
	if (field.endsWith('Date')) {
		// console.log('date,field:%o,%o,-->%o', field, originalValue, value);
		let v2 = Ext.Date.dateFormat(value, 'Y-m-d');
		// console.log('v2:%o,originalValue:%o,%o', v2, originalValue,v2 == originalValue);
		if (v2 == originalValue) {
			return false;
		}
	}
	return true;
}

function changeRowClass(record, rowIndex, rowParams, store) {
	let status = record.data && record.data.status;
	let css = '';
	if (undefined != status) {
		switch(status){
			case 0:
				css='x-grid-task0';
				break;
			case 1:
				css='x-grid-task1';
				break;
			case 2:
				css='x-grid-task2';
				break;
			case 3:
				css='x-grid-task3';
				break;
			case 4:
				css='x-grid-task4';
				break;
			case 5:
				css='x-grid-task5';
				break;
			case 6:
				css='x-grid-task6';
				break;
			case 7:
				css='x-grid-task7';
				break;
			case 8:
				css='x-grid-task8';
				break;
			case 9:
				css='x-grid-task9';
				break;
			case 10:
				css='x-grid-task10';
				break;
		}
	}
	return css;
}